<?php

namespace App\Api\Http\ApiControllers;

use App\Application\OrderService;
use App\Exceptions\Item\OrderException;
use App\Repositories\Order\OrderRepositoryInterface;
use Illuminate\Http\Request;

class UserOrderController extends Controller
{
    /**
     * @var OrderService
     */
    protected $order_service;

    public function __construct(OrderService $order_service)
    {
        $this->order_service = $order_service;
    }

    /**
     * 用户订单列表
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $per_page = $request->get('per_page', 10);
        $data = $this->order_service->userOrders(access()->id(), $per_page);

        return response()->json($data);
    }

    /**
     * 订单详情
     *
     * @param $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $info = $this->order_service->show($id, access()->id());

        return response()->json($info);
    }

    /**
     * 用户订单申述
     *
     * @param         $id
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws OrderException
     */
    public function appeal($id, Request $request)
    {
        $this->order_service->show($id, access()->id());

        $content = $request->get('content');
        if (mb_strlen($content) < 10) {
            throw new OrderException(OrderException::APPEAL_CONTENT_LENGTH);
        }

        /** @var OrderRepositoryInterface $repository */
        $repository = App(OrderRepositoryInterface::class);

        if ($repository->orderAppeal($id)) {
            throw new OrderException(OrderException::APPEAL_CONTENT_APPEALED);
        }

        $repository->storeOrderAppeal($id, $content);

        return response('', 201);
    }

    /**
     * 订单留言
     *
     * @param         $id
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws OrderException
     */
    public function leaveMessage($id, Request $request)
    {
        $this->order_service->show($id, access()->id());

        $content = $request->get('content');
        if (mb_strlen($content) < 1) {
            throw new OrderException(OrderException::MESSAGE_CONTENT_LENGTH);
        }
        if (mb_strlen($content) > 200) {
            throw new OrderException(OrderException::MESSAGE_CONTENT_LENGTH_LONG);
        }

        /** @var OrderRepositoryInterface $repository */
        $repository = App(OrderRepositoryInterface::class);

        if ($repository->orderMessage($id)) {
            throw new OrderException(OrderException::MESSAGE_CONTENT_APPEALED);
        }

        $repository->storeUserMessage($id, $content);

        return response('', 201);
    }
}
